package DB;

import Models.Ordre;
import Models.VareSamling;
import java.sql.Connection;
import java.sql.Statement;

public class DBOrdre
{
	private Connection con;

	public DBOrdre()
	{
		con = DBConnection.getInstance().getDBcon();
	}

	private int addVareToOrdre(Ordre ordre, int vareId, int antal)
	{
		int rc = -1;
		String query="INSERT INTO VareOrdrer (ordre, vare, antal) VALUES ('";
		query += ordre.getId() + "', " + vareId + ", " + antal + ")";
		System.out.println("insert : " + query);
		
		try
		{
			Statement stmt = con.createStatement();
			stmt.setQueryTimeout(5);
			rc = stmt.executeUpdate(query);
			stmt.close();
		}
		catch(Exception ex){
			System.out.println("Insert exception in vare db: "+ex.getMessage());
		}
		return rc;
	}

	public int insertOrdre(Ordre ordre)
	{
		int rc = -1;
		String query="INSERT INTO Ordrer (dato, forsendelsesmåde, portogebyr, leveringsdato, kunde, faktura) VALUES ('";
		query += ordre.getDato() + "', " + ordre.getForsendelsesmåde() + ", " + ordre.getPortogebyr() + ", " + ordre.getLeveringsdato() + ", " + ordre.getKunde().getId() + ", " + ordre.getFaktura().getId() + ")";
		System.out.println("insert : " + query);

		try
		{
			Statement stmt = con.createStatement();
			stmt.setQueryTimeout(5);
			rc = stmt.executeUpdate(query);
			stmt.close();

			for(VareSamling vs : ordre.getVarer())
			{
				this.addVareToOrdre(ordre, vs.getVare().getId(), vs.getAntal());
			}
		}
		catch(Exception ex){
			System.out.println("Insert exception in vare db: "+ex.getMessage());
		}
		return rc;
	}
}
